package com.njbw.user.delayQueue;

import com.alibaba.fastjson.JSON;
import com.njbw.redis.util.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

@Log4j2
@Service
public class MassMailTaskService {

    @Resource
    private RedisUtil redisUtil;

    private static final String MASS_MAIL_TASK_KEY = "massTaskMail";

    /**
     * 入队列
     */
    public void pushMassMailTaskQueue(MassMailTask massMailTask) {
        LocalDateTime startTime = massMailTask.getStartTime();
        if (startTime == null) {
            return;
        }
        if (startTime.isBefore(LocalDateTime.now()) || startTime.isEqual(LocalDateTime.now())) {
            return;
        }
        if (log.isInfoEnabled()) {
            log.info("定时任务加入队列，massMailTask: {}", JSON.toJSONString(massMailTask));
        }
        redisUtil.zAdd(MASS_MAIL_TASK_KEY, massMailTask.getTaskId().toString(), startTime.toInstant(ZoneOffset.ofTotalSeconds(8 * 60 * 60)).toEpochMilli());
    }

    /**
     * 从队列中取
     */
    public Set<Long> pollMassMailTaskQueue() {
        Set<String> taskIdSet = redisUtil.rangeByScore(MASS_MAIL_TASK_KEY, 0, System.currentTimeMillis());
        if (CollectionUtils.isEmpty(taskIdSet)) {
            return Collections.emptySet();
        }
        redisUtil.removeZset(MASS_MAIL_TASK_KEY, taskIdSet);
        return taskIdSet.stream().map(Long::parseLong).collect(Collectors.toSet());
    }
}
